package com.sinodata.bsm.cicp.collector.file;

import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Title: DirSchedule
 * </p>
 * <p>
 * Description: 检测某个路径下的文件进展.<br>
 * 应用环境是这样的:在某个路径(临时)下有数量非常大的文件数量,然而还必须需要监控这个路径下有进展.<br>
 * 在文件数量极大的情况下无论使用什么样的命令想获得最新的文件及其基本属性都是非常的困难的.<br>
 * 但是在此目录下的文件发生了添加和删除的时候,此路径的最近一次修改时间是会反映到改路径的基本属性上的.<br>
 * 所以直接导致了此采集程序的产生,此采集程序:<br>
 * 1,参数仅为被监控进展的路径<br>
 * 2,返回结果为[1]路径Modify time; [2]当前时间.<br>
 * 
 */
public class DirSchedule extends Collector {
    private static Logger logger = Logger.getLogger(DirSchedule.class);

    /**
     * 采集程序主体,通过此采集采集获得文件路径的Modify time及当前时间
     *
     * @param resAtt
     *            ResAttributeValValue[] 文件路径
     * @param ip
     *            String 被监控节点的IP地址
     * @return List 采集结果
     * @throws CollectorException 
     */

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String fullpath = this.getParamMap().get("File Path");//文件路径
        String shell = "echo `lsdir \"" + fullpath + "\"; date +%Y%m%d%H%M%S`";
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, shell, 0, 300);
            if (reader == null) {
                logger.error("file not found");
                return null;
            }
            String readLine = reader.readLine();

            List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();

            String[] propMetas = getPropMeta();
            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

            if (readLine == null || readLine.trim().equals("命令参数不对")) {
                return null;
            }
            readLine = readLine.trim();
            String[] tmp = readLine.split(" ");
            if (tmp.length != 4) {
                return null;
            }
            propValues[0] = ResPropertyValue.createPropValue(getFormatDate(getDateMillis(tmp[2].trim())), propMetas[0]);
            propValues[1] = ResPropertyValue.createPropValue(getFormatDate(getDateMillis(tmp[3].trim())), propMetas[1]);

            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } catch (IOException e) {
            logger.error("read file error ", e);
            throw new CollectorException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (java.io.IOException e) {
                    logger.debug("failed to close inputstream ", e);
                    throw new CollectorException(e);
                }
            }
        }
    }

    private long getDateMillis(String date) {
        Calendar calendar = Calendar.getInstance();
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(4, 6)) - 1;
        int day = Integer.parseInt(date.substring(6, 8));
        int hour = Integer.parseInt(date.substring(8, 10));
        int minute = Integer.parseInt(date.substring(10, 12));
        int second = Integer.parseInt(date.substring(12));
        calendar.set(year, month, day, hour, minute, second);
        return calendar.getTimeInMillis(); // 转换为毫秒
    }

    private String getFormatDate(long date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date(date));
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "File Path" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "处理时间", "采集时间" };
        //        return new String[] { "Process_Time", "Collect_Time" };
        return new String[] { "$1", "$2" };
    }
}
